package com.lanju.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lanju.common.Contants;
import com.lanju.entity.User;
import com.lanju.model.AccessToken;
import com.lanju.model.ResultModel;
import com.lanju.service.JedisService;
import com.lanju.service.UserService;
import com.lanju.util.CommonUtil;
import com.lanju.util.WeiXinUtil;

/**
 * 微信各种接口
 * 
 * @author zengqd
 * @CrateTime 2018年9月23日 下午6:33:14
 */
@Controller
@RequestMapping("weixinImpl")
public class WeiXinInterfaceController {

	private static final Logger LOGGER = LoggerFactory.getLogger(WeiXinInterfaceController.class);

	@Autowired
	UserService userService;

	@Resource
	JedisService jedisService;
	
	private final Gson gson = new GsonBuilder().setDateFormat("yyyyMMddHHmmss").create();
	/**
	 * 微信登录
	 * 
	 * @param req
	 * @param resp
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@RequestMapping("/login")
	@ResponseBody
	public void  Login(HttpServletRequest req, HttpServletResponse resp)
			throws ClientProtocolException, IOException {
		String url = Contants.WX_AUTH_URL;
		resp.sendRedirect(url);
	}

	@SuppressWarnings("unused")
	@RequestMapping("callBack")
	@ResponseBody
	public void  CallBack(HttpServletRequest req, HttpServletResponse resp,HttpSession session)
			throws ClientProtocolException, IOException {
		Map<String, Object> result=new HashMap<>();
		User user = (User) session.getAttribute("userModel");
		System.out.println("user的手机号码是："+user.getPhone());
		String code = req.getParameter("code");// 获取code
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ Contants.APPID + "&secret=" + Contants.APPSECRET + "&code="+ code + "&grant_type=authorization_code";
		JSONObject jsonObject = WeiXinUtil.doGetStr(url);
		String openid = jsonObject.getString("openid");
		String token = jsonObject.getString("access_token");
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+ token + "&openid=" + openid + "&lang=zh_CN";
		JSONObject userInfo = WeiXinUtil.doGetStr(infoUrl);
		Contants.openid = userInfo.getString("openid");
		//保存用户信息
		Map<String, Object> param=new HashMap<>();
		param.put("openId", userInfo.get("openid").toString());
		if(user==null){//用户未登陆,找该微信用户是否存在
			User user_=userService.getByOpenId(param);
			if(user_!=null){
				LOGGER.info("微信用户已存在");
			}else{//游客身份
				User weixinUser =new User();
				weixinUser.setOpenId(userInfo.get("openid").toString());
				weixinUser.setHeadImg(userInfo.get("headimgurl").toString());
				weixinUser.setNickName(userInfo.get("nickname").toString());
				weixinUser.setSex(Integer.valueOf(userInfo.get("sex").toString()));
				weixinUser.setStatus(1);
				weixinUser.setUserCode(UUID.randomUUID().toString());
				ResultModel  rmodel=userService.add(user_);
				LOGGER.info("返回信息："+rmodel.getContent());
			}
			
		}else{//用户已登录
			LOGGER.info("获取的手机号码是："+user.getPhone());
			if(user.getOpenId() == null){//绑定
				LOGGER.info("用户已登陆,开始绑定");
				 user.setHeadImg(userInfo.get("headimgurl").toString());
				 user.setNickName(userInfo.get("nickname").toString());
				 user.setOpenId(userInfo.get("openid").toString());
				 user.setSex(Integer.valueOf(userInfo.get("sex").toString()));
				 ResultModel model= userService.edit(user);
				 LOGGER.info(model.getResultCode().toString());
				 sendTemplateMessage(req, resp, userInfo.get("openid").toString(), "bMcoHBuCSPvYCND_FuXCzMhxwSxdGPCbjwVI9V_yjOo","蓝居用户："+user.getNickName(),user.getNickName(), user.getPhone(), "暂无", userInfo.get("nickname").toString(), "不详","蓝居用户微信绑定信息");
				 session.setAttribute("userModel", user);
				 System.out.println("[" + user.getNickName()+ "] has auth success login");
			}else{
				LOGGER.info("用户已绑定微信，无需绑定");
			}
		}
		String redirecturl="../jsp/home.html";
		resp.sendRedirect(redirecturl);
	}

	/**
	 * 获取普通token,供请求网页tikect使用
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@RequestMapping("/getAccessToken")
	public AccessToken getAccessToken() throws ClientProtocolException,
			IOException {
//		HttpSession httpSession = req.getSession();
		AccessToken token = new AccessToken();
		String url = Contants.TICKET_ACCESS_TOKEN_URL;
		JSONObject jsonObject = WeiXinUtil.doGetStr(url);// 使用刚刚写的doGet方法接收结果
		if (jsonObject != null) { // 如果返回不为空，将返回结果封装进AccessToken实体类
			token.setToken(jsonObject.getString("access_token"));// 取出access_token
			token.setExpiresIn(jsonObject.getInt("expires_in"));// 取出access_token的有效期
//			httpSession.setAttribute("access_token", token.getToken());
			Contants.ACCESS_TOKEN = jsonObject.getString("access_token");// 正式环境就去掉
			getJsapi_ticket();
		}
		return token;
	}

	/**
	 * 获取Jsapi_ticket
	 * 
	 * @param req
	 * @param resp
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@RequestMapping("getJsapi_ticket")
	public void getJsapi_ticket()
			throws ClientProtocolException, IOException {
		try {
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ Contants.ACCESS_TOKEN + "&type=jsapi";
			JSONObject jsonObject = WeiXinUtil.doGetStr(url);
			String ticket = jsonObject.getString("ticket");
			String time = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date());
			Contants.JSAPI_TICKET_TIME = time;
			Contants.JSAPI_TICKET = ticket;
			String timestamp = String
					.valueOf(System.currentTimeMillis() / 1000);// 随机生成的时间戳
			Contants.timestamp = timestamp;
			String noncestr = CommonUtil.getRandomString(16);// 生成的16位随机码
			Contants.noncestr = noncestr;
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	/**
	 * 
	 * @param req
	 * @param resp
	 * @param url
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "getEncryptJsapiTicket", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getEncryptJsapiTicket(HttpServletRequest req,
			HttpServletResponse resp, @RequestParam("url") String url)
			throws UnsupportedEncodingException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Date savejsapiTime;// 上一次获取的jsapi_ticket
		String jsapiticket = Contants.JSAPI_TICKET;

		try {
			if (jsapiticket != null && jsapiticket != "") {
				String url1 = java.net.URLDecoder.decode(url, "UTF-8");// 在调用js的页面完整URL
				System.out.println("url1=" + url1);
				// 接下来判断jsapiticket是否超时，如果超时则重新申请一个token再获取一个ticket
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				savejsapiTime = sdf.parse(Contants.JSAPI_TICKET_TIME);
				savejsapiTime.setHours(savejsapiTime.getHours() + 2);
				System.out.println("上一次获取的jsapi_ticket===" + jsapiticket);
				Date curdate = new Date();
				System.out.println("当前时间curdate===" + curdate);
				int result = curdate.compareTo(savejsapiTime);// 1：还没超时，-1超时
				System.out.println("是否小于当前时间" + result);
				if (result == -1 || result == 0) {// ticket未超时
					System.out.println("未超时");
				} else if (result == 1) {// ticket超时
					getAccessToken();
				}
				System.out.println("是否小于当前时间" + result);
				String signature = getSignature(url1, Contants.timestamp,
						Contants.noncestr, Contants.JSAPI_TICKET);// 开始进行sha1签名
				resultMap.put("nonce", Contants.noncestr);
				resultMap.put("signature", signature);
				resultMap.put("timestamp", Contants.timestamp);
				return resultMap;
			} else {
				getAccessToken();
				getEncryptJsapiTicket(req, resp, url);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 签合同
	 * @param req
	 * @param resp
	 * @param openid
	 *            粉丝的openid
	 * @param templateId
	 *            信息模版id
	 * @param username
	 *            内容名称
	 * @param project
	 *            项目
	 * @param point
	 *            巡检点
	 * @param optuser
	 *            操作时间
	 * @param remark
	 *            备注
	 * @return
	 */
	@RequestMapping("/sendTemplateMessage")
	@ResponseBody
	public Map<String, Object> sendTemplateMessage(HttpServletRequest req,
			HttpServletResponse resp, @RequestParam("openid") String openid,
			@RequestParam("templateId") String templateId,
			@RequestParam("first") String first,
			@RequestParam("keyword1") String keyword1,
			@RequestParam("keyword2") String keyword2,
			@RequestParam("keyword3") String keyword3,
			@RequestParam("keyword4") String keyword4,
			@RequestParam("keyword5") String keyword5,
			@RequestParam("remark") String remark) {
		Map<String, Object> map = new HashMap<>();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
				+ Contants.ACCESS_TOKEN;
		String data = "{\"touser\":\""
				+ openid
				+ "\", \"template_id\":\""
				+ templateId
				+ "\",\"topcolor\":\"#FF0000\", \"data\":{\"first\": { \"value\":\""
				+ first
				+ "\",\"color\":\"#0195F7\"},\"keyword1\": { \"value\":\""
				+ keyword1
				+ "\",\"color\":\"#173177\"},\"keyword2\": { \"value\":\""
				+ keyword2 + "\",\"color\":\"#000\"},\"keyword3\": { \"value\":\""
				+ keyword3
				+ "\",\"color\":\"#000\"},\"keyword4\": { \"value\":\""
				+ keyword4 + "\",\"color\":\"#000\"},\"keyword5\": { \"value\":\""
				+ keyword5 + "\",\"color\":\"#000\"},\"remark\": { \"value\":\""
				+ remark + "\",\"color\":\"#000\"}}}";
		Date savejsapiTime;
		String jsapiticket = Contants.JSAPI_TICKET;
		try {
			if (jsapiticket != null && jsapiticket != "") {
				// 接下来判断jsapiticket是否超时，如果超时则重新申请一个token再获取一个ticket
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				savejsapiTime = sdf.parse(Contants.JSAPI_TICKET_TIME);
				savejsapiTime.setHours(savejsapiTime.getHours() + 2);
				Date curdate = new Date();
				int result = curdate.compareTo(savejsapiTime);// 1：还没超时，-1超时
				if (result == -1 || result == 0) {// ticket未超时
					System.out.println("未超时");
				} else if (result == 1) {// ticket超时
					getAccessToken();
				}
			} else {
				getAccessToken();
			}
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			JSONObject obj = WeiXinUtil.doPostStr(url, data);
			map.put("rows", obj);
			map.put("list", templateId);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	
	
	
	/**
	 * 获取菜单列表
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/getMenu")
	@ResponseBody
	public Map<String, Object> getMenu(HttpServletRequest req,
			HttpServletResponse resp) {
		Map<String, Object> map = new HashMap<>();
		String url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+ Contants.ACCESS_TOKEN;
		try {
			JSONObject obj = WeiXinUtil.doGetStr(url);
			System.out.println("返回的结果是");
			System.out.println(obj);
			map.put("rows", obj);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 创建菜单
	 * 
	 * @return
	 */
	@RequestMapping("/createMenu")
	@ResponseBody
	public Map<String, Object> createMenu(HttpServletRequest req,
			HttpServletResponse resp) {
		Map<String, Object> map = new HashMap<>();
		String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="
				+ Contants.ACCESS_TOKEN;
		String data = "{\"button\":[{\"name\":\"了解蓝居\",\"sub_button\":[ { \"type\":\"view\",\"name\":\"蓝居简介\",\"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/liaojieLanJu.html?tab=tab1\" },{\"type\":\"view\",\"name\":\"托管介绍\",  \"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/liaojieLanJu.html?tab=tab2\"},{\"type\":\"view\",\"name\":\"租房介绍\",  \"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/liaojieLanJu.html?tab=tab3\"}] }, {\"type\":\"view\",\"name\":\"蓝居首页\",  \"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/home.html\"},{\"name\":\"蓝居服务\",\"sub_button\":[ { \"type\":\"view\",\"name\":\"业主服务\",\"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/zukeKongjian.html\" },{ \"type\":\"view\",\"name\":\"租客服务\",\"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/zukeKongjian.html\" },{ \"type\":\"view\",\"name\":\"服务查询\",\"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/service/serviceList.html?serviceType=1\" },{ \"type\":\"view\",\"name\":\"保洁预约\",\"url\":\"http://lanjushiye.com.cn/LanJuPublic/jsp/service/servicePackage.html?serviceType=1\" },{ \"type\":\"click\",\"name\":\"联系客服\",\"key\":\"contact\" }] }] }]}";
		try {
			JSONObject obj = WeiXinUtil.doPostStr(url, data);
			map.put("rows", obj);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 删除菜单
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("/delMenu")
	@ResponseBody
	public Map<String, Object> delMenu(HttpServletRequest req,
			HttpServletResponse resp) {
		Map<String, Object> map = new HashMap<>();
		String url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="
				+ Contants.ACCESS_TOKEN;
		try {
			JSONObject obj = WeiXinUtil.doGetStr(url);
			map.put("rows", obj);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 生成签名,该签名用于调用JS-SDK
	 * 
	 * @param url
	 * @param timeStamp
	 * @param nonceStr
	 * @return
	 */
	public static String getSignature(String url, String timeStamp,
			String nonceStr, String jsapiticket) {

		// 所有待签名参数按照字段名的ASCII
		// 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1：
		String signValue = "jsapi_ticket=" + jsapiticket + "&noncestr="
				+ nonceStr + "&timestamp=" + timeStamp + "&url=" + url;
		String signature = DigestUtils.sha1Hex(signValue);
		return signature;
	}

	@RequestMapping("/sendHeTongMessage")
	@ResponseBody
	public Map<String, Object> sendHeTongMessage(HttpServletRequest req,
			HttpServletResponse resp,
			@RequestParam("templateId") String templateId,
			@RequestParam("userId") String userId,
			@RequestParam("title") String title,
			@RequestParam("agreementName") String agreementName,
			@RequestParam("agreementType") String agreementType,
			@RequestParam("price") String price,
			@RequestParam("floor") String floor,
			@RequestParam("signUserName") String signUserName,
			@RequestParam("remark") String remark) {
		Map<String, Object> map = new HashMap<>();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Map<String, Object> phoneMap = new HashMap<>();
		phoneMap.put("userId", userId);
		int flag= 0;
		User user = userService.getById(userId);
		if(user !=null && user.getOpenId()==null){
			map.put("success", false);
			map.put("msg", "用户尚未绑定微信，请联系用户绑定微信再操作");
			return map;
		}else if(user==null){
			map.put("success", false);
			map.put("msg", "找不到用户");
			return map;
		}
		flag = user.getFlag();
		String url_=null;
		if(flag ==1){
			url_ = "http://lanjushiye.com.cn/LanJuPublic/jsp/contractTerms.html?contractId=";
		}else{
			url_ = "http://lanjushiye.com.cn/LanJuPublic/jsp/renterContractTerms.html?contractId=";
		}
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
				+ Contants.ACCESS_TOKEN;
		String data = "{\"touser\":\""
				+ user.getOpenId()
				+ "\", \"template_id\":\""
				+ templateId
				+ "\",\"url\":\""+url_+""
				+ title
				+ "\",\"topcolor\":\"#FF0000\", \"data\":{\"first\": { \"value\":\""
				+ signUserName
				+ "\",\"color\":\"#173177\"},\"keyword1\": { \"value\":\""
				+ title
				+ "\",\"color\":\"#173177\"},\"keyword2\": { \"value\":\""
				+ price + "\",\"color\":\"#000\"},\"keyword3\": { \"value\":\""
				+ floor + "\",\"color\":\"#000\"},\"keyword4\": { \"value\":\""
				+ sdf1.format(new Date())
				+ "\",\"color\":\"#000\"},\"keyword5\": { \"value\":\""
				+ signUserName
				+ "\",\"color\":\"#000\"},\"remark\": { \"value\":\"" + remark
				+ "\",\"color\":\"#000\"}}}";
		Date savejsapiTime;
		String jsapiticket = Contants.JSAPI_TICKET;
		try {
			if (jsapiticket != null && jsapiticket != "") {
				// 接下来判断jsapiticket是否超时，如果超时则重新申请一个token再获取一个ticket
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				savejsapiTime = sdf.parse(Contants.JSAPI_TICKET_TIME);
				savejsapiTime.setHours(savejsapiTime.getHours() + 2);
				Date curdate = new Date();
				int result = curdate.compareTo(savejsapiTime);// 1：还没超时，-1超时
				if (result == -1 || result == 0) {// ticket未超时
					System.out.println("未超时");
				} else if (result == 1) {// ticket超时
					getAccessToken();
				}
			} else {
				getAccessToken();
			}
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			JSONObject obj = WeiXinUtil.doPostStr(url, data);
			map.put("rows", obj);
			map.put("list", templateId);
			map.put("success", true);
			map.put("msg", "发送成功");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "发送失败");
		} catch (IOException e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "发送失败");
		}
		return map;
	}
	
	   /**
     * 获取素材列表
     *
     * @return
     * @throws IOException
     */
	@RequestMapping("getMaterialList")
	@ResponseBody
    public JSONObject getMaterialList(String type, int offset, int count) throws IOException {
        String apiurl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
        String access_token = Contants.ACCESS_TOKEN;
        String url = apiurl.replace("ACCESS_TOKEN", access_token);
        JSONObject params = new JSONObject();
        params.element("type", type);
        params.element("offset", offset);
        params.element("count", count);
        JSONObject jsonObject = WeiXinUtil.doPostStr(url, params.toString());
        return jsonObject;
    }

}
